import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'
import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef, useState } from 'react'
import { ScrollViewWrapper } from './style'

const ScrollView = memo(props => {
  const [showLeft, setShowLeft] = useState(false)
  const [showRight, setShowRight] = useState(false)
  const [posIndex, setPosIndex] = useState(0)
  /* 组件渲染完毕，判断是否显示右边按钮 */
  const scrollContentRef = useRef()
  /* 利用useRef让函数组件更新totalDistanceRef不更新 */
  const totalDistanceRef = useRef()
  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth //可滚动的宽度
    const clientWidth = scrollContentRef.current.clientWidth //本身占据的宽度
    totalDistanceRef.current = scrollWidth - clientWidth
    setShowRight(totalDistanceRef.current > 0)
  }, [props.children]) //一旦props.children中的数据发生改变就重新执行useEffect中的代码
  /* 事件处理的逻辑 */

  function controlClickHandle(isRight) {
    const newIndex = isRight ? posIndex + 1 : posIndex - 1
    const newEl = scrollContentRef.current.children[newIndex]
    const newElOffsetLeft = newEl.offsetLeft //offsetLeft是相对于最近的定位父元素
    scrollContentRef.current.style.transform = `translate(-${newElOffsetLeft}px)`
    setPosIndex(newIndex)
    /* 是否继续显示右边按钮 */
    /* 左边的偏移量大于可滚动距离就隐藏右边点击按钮 */
    setShowRight(totalDistanceRef.current - newElOffsetLeft > 0)
    /* 左边按钮显示 */
    setShowLeft(newElOffsetLeft > 0)
  }
  return (
    <ScrollViewWrapper>
      {showLeft && (
        <div className='control left' onClick={() => controlClickHandle(false)}>
          <IconArrowLeft></IconArrowLeft>
        </div>
      )}
      {showRight && (
        <div className='control right' onClick={() => controlClickHandle(true)}>
          <IconArrowRight></IconArrowRight>
        </div>
      )}
      <div className='scroll'>
        <div className='scroll-content' ref={scrollContentRef}>
          {props.children}
        </div>
      </div>
    </ScrollViewWrapper>
  )
})

ScrollView.propTypes = {
  children: PropTypes.array
}

export default ScrollView
